/*
 * Copyright (c) 2016. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Layout;
import android.text.SpannableString;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.yiji.www.frameworks.utils.DensityUtils;

import java.math.BigDecimal;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.delivery.order.view.CancelReasonPopupView;
import cn.com.dhc.danlu.activity.delivery.order.view.FullScreenPriceChangeNotePopview;
import cn.com.dhc.danlu.activity.delivery.order.view.OrderFunctionView;
import cn.com.dhc.danlu.activity.delivery.order.viewholder.OrderStatusHeaderWrapper;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.popup.MerchPricePopupView;
import cn.com.dhc.danlu.widget.popup.PromotionDetailPopup;
import cn.com.dhc.danlu.yijifu.YjfPayEngine;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.oper.OrderOperCancelRequest;
import cn.com.hd.mall.web.webservices.entity.request.oper.OrderOperReceiveRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.OrderDetailRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.OrderLogRequest;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderChangeNote;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderDetailResponse;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderDetailResponse.OrderDetailBean;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderDetailResponse.OrderDetailBean.MerchListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: MuWei<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2015/02/05 00:00<br/>
 *
 * <p>
 * 订单详细画面
 * </p>
 */
@SuppressWarnings("ALL")
public class DeliveryDetailActivity extends BaseActivity {
    /**
     * 订单号
     */
    private TextView txtOrderBigNum;
    /**
     * 子订单号
     */
    private TextView txtOrderSmallNum;
    /**
     * 下单时间
     */
    private TextView txtPlaceOrderTime;
    /**
     * 支付时间
     */
    private TextView txtPayTime;
    /**
     * 配送商
     */
    private TextView txtPlaceOrderDispatch;
    /**
     * 收货人
     */
    private TextView txtReceiverName;
    /**
     * 电话
     */
    private TextView txtReceiverTel;
    /**
     * 地址
     */
    private TextView txtReceiverAddress;
    /**
     * 发票信息
     */
    private TextView txtOrderInvoice;
    /**
     * 支付方式
     */
    private TextView txtOrderPayment;
    /**
     * 买家留言
     */
    private TextView txtBuyerWords;
    /**
     * 商品容器
     */
    private LinearLayout llytShopContainer;
    /**
     * 商品数量
     */
    private int shopNum = 0;
    /**
     * 商品总价
     */
    private int allPrice = 0;
    /**
     * 买家留言跳转
     */
    private RelativeLayout rlytOrderBuyerWords;
    /**
     * 发票详情跳转
     */
    private RelativeLayout rlytOrderInvoiceMsg;

    /**
     * 发票进入图片
     */
    private ImageView imgOrderDetail;

    /**
     * 意图对象
     */
    private Intent intent;

    /**
     * 订单id
     */
    private String orderId;
    private String orderNo;
    private OrderDetailBean orderDetail;

    /**
     * 促销元素
     */
    private LinearLayout llPromotionArea;

    /**
     * 改价元素
     */
    private RelativeLayout rlytGjLayout;
    private TextView txtGjValue;

    // 价格区域
    private RelativeLayout mRlOrderOriginPrice;
    private RelativeLayout mRlCuxiaoDis;
    private RelativeLayout mRlGoodsCouponDis;
    private RelativeLayout mRlDealersEnvelopDis;
    private RelativeLayout mRlDanluEnvelopDis;

    /**
     * 总价元素
     */
    private RelativeLayout rlytTotalLayout;
    private TextView txtTotalValue;

    /**
     * 红包折扣
     */
    private TextView tv_envelop;
    private LinearLayout llPayContainer;

    private TextView tvOrderOriginPrice;
    private TextView tvCuxiaoDiscount;
    private TextView tvCouponDiscount;
    private TextView tvDealerEnvelopDed;
    private LinearLayout llytBack;

    private OrderStatusHeaderWrapper headerWrapper;
    private String cancleReason;

    private OrderFunctionView ofvOrder;
    private OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.llytBack:
                    finish();
                    break;

                // 跳转发票详情页
                case R.id.rlytOrderInvoiceMsg:
                    intent.setClass(DeliveryDetailActivity.this, DeliveryInvoiceMessageActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    break;

                // 跳转卖家留言页
                case R.id.rlytOrderBuyerWords:
                    intent.setClass(DeliveryDetailActivity.this, DeliveryBuyerLeaveWordsActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };
    private YjfPayEngine payEngine;

    public static void startSelf(Context context, String orderNo) {
        Intent intent = new Intent(context, DeliveryDetailActivity.class);
        intent.putExtra(CommonConst.MyOrderConst.SMALL_ORDER, orderNo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_detail);

        // 初始化控件
        initViews();
        initData();
        setListener();
    }

    @Override
    protected String getActivityTitle() {
        return getString(R.string.page_delivery_order_detail);
    }

    /**
     * 画面初始化
     */
    private void initData() {
        // 意图对象初始化
        intent = new Intent();
        // 添加点击监听
        setListener();
        // 获取前画面传递的订单Id
        orderId = getIntent().getStringExtra(CommonConst.MyOrderConst.SMALL_ORDER);
        // 获取前画面传递的订单主键
        // 订单主键
        orderNo = getIntent().getStringExtra(CommonConst.MyOrderConst.SMALL_ORDER_P_KEY);
        // 获取卖家是否有易极付账户
        // 根据订单Id，获取订单详情
        getOrderDetail();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        rlytOrderBuyerWords.setOnClickListener(clickListener);
        rlytOrderInvoiceMsg.setOnClickListener(clickListener);

        ofvOrder.setOrderOperatorCallback(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_order_pay) {
                    payAction();
                } else if (v.getId() == R.id.btn_order_receive) {
                    createOrderReceiveDialog();
                } else if (v.getId() == R.id.btn_order_split) {
                    OrderSplitListActivity.startSelf(DeliveryDetailActivity.this, orderDetail.getOrderNo());
                } else if (v.getId() == R.id.btn_order_change_price_note) {
                    viewOrderPriceChangeNote();
                } else if (v.getId() == R.id.btn_order_track) {
                    skipOrderTrackActivity();
                } else if (v.getId() == R.id.btn_order_cancel) {
                    cancelDeal();
                }
            }
        });
    }

    private void cancelDeal() {
        CancelReasonPopupView popupView = new CancelReasonPopupView(this, new CancelReasonPopupView.ICancelOrderListener() {
            @Override
            public void onCancel(final String reason) {
                headerWrapper.setCancelReason(reason);
                // 取消交易请求类
                OrderOperCancelRequest request = new OrderOperCancelRequest();
                request.setToken(agent.getToken()); // 设置token
                request.setCancelReason (reason);
                request.setPaymentNo(orderDetail.getPaymentNo()); // 设置大订单
                request.setPayType(orderDetail.getPayType()); // 设置支付方式
                // 设置cancleType
                String cancleType = orderDetail.getButtomList().split("")[4];
                final String orderStatus = orderDetail.getOrderStatus();
                request.setCancelType(cancleType);
                agent.getApi()
                        .orderDealCancle(request)
                        .compose(OperatorUtils.defaultSchedulers())
                        .subscribe(new GeneralBusinessObserver<BaseResponse>(DeliveryDetailActivity.this, R.string.tips_order_cancel) {
                            @Override
                            protected void onSuccess(BaseResponse baseResponse) {
                                if (orderStatus.equals("C017")) {
                                    ToastUtil.getInstance().show(R.string.myself_order_deal_cancle_comfirm);
                                } else {
                                    ToastUtil.getInstance().show(R.string.myself_order_deal_cancle_success);
                                }
                                getOrderDetail();
                            }

                            @Override
                            protected String parseBussinessException(String code) {
                                return code.equals("1") ? "订单状态发生变化取消失败" : "订单取消失败";
                            }

                            @Override
                            protected void onAlertTips(String displayMessage) {
                                ToastUtil.getInstance().show(displayMessage);
                            }
                        });
            }
        });
        popupView.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    private void payAction() {
        if (null == payEngine) {
            payEngine = new YjfPayEngine(this, null, false);
        }
        payEngine.payAction(orderDetail.getPaymentNo());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (YjfPayEngine.YIJIFU_PAYYMENT_CODE == requestCode) {
            // 处理支付结果
            payEngine.handlerPayResult(requestCode, resultCode, data);
        }
        if (YjfPayEngine.YIJIFU_REGISTER_CODE == requestCode) {
            boolean registerSuccessFlag = false;
            if (data != null) {
                registerSuccessFlag = data.getBooleanExtra(CommonConst.BroadcastAction.BROADCAST_GET_YJF_REGISTER_ACTION, false);
            }
            // 处理注册结果
            if (registerSuccessFlag) {
                payEngine.handlerPayResult(requestCode, resultCode, data);
                finishActivity(YjfPayEngine.YIJIFU_REGISTER_CODE);
            } else {
                finishActivity(YjfPayEngine.YIJIFU_REGISTER_CODE);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 查看经销商改价备注
     */
    private void viewOrderPriceChangeNote() {
        OrderLogRequest req = new OrderLogRequest();
        req.setOrderNo(orderDetail.getOrderNo());
        req.setToken(agent.getToken());
        agent.getApi().getOrderChangePriceCommentInfo(req)
                .compose(OperatorUtils.<OrderChangeNote> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<OrderChangeNote>(DeliveryDetailActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(OrderChangeNote orderChangeNote) {
                        FullScreenPriceChangeNotePopview popview = new FullScreenPriceChangeNotePopview(DeliveryDetailActivity.this);
                        popview.refreshView(orderChangeNote);
                        popview.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, CommonUtils.getStatusBarHeight (DeliveryDetailActivity.this));
                    }
                });
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     *         订单Id
     */
    private void getOrderDetail() {
        // form
        OrderDetailRequest form = new OrderDetailRequest();

        // 传递参数：订单Id
        form.setOrderNo(orderId);
        // 设置子订单主键
        form.setOrderPk(orderNo);
        // 传递参数：token
        form.setToken(agent.getToken());

        agent.getApi()
                .getTerminalOrderDetail(form)
                .compose(OperatorUtils.<OrderDetailResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<OrderDetailResponse>() {
                    @Override
                    protected void onSuccess(OrderDetailResponse model) {
                        orderDetail = model.getOrderDetail();
                        // 设置数据
                        setOrderDetailData(orderDetail);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
        txtOrderBigNum = (TextView) findViewById(R.id.txtOrderBigNum);
        txtOrderSmallNum = (TextView) findViewById(R.id.txtOrderSmallNum);
        txtPlaceOrderTime = (TextView) findViewById(R.id.txtPlaceOrderTime);
        txtPayTime = (TextView) findViewById(R.id.txtPayTime);
        txtPlaceOrderDispatch = (TextView) findViewById(R.id.txtPlaceOrderDispatch);
        txtReceiverName = (TextView) findViewById(R.id.txtReceiverName);
        txtReceiverTel = (TextView) findViewById(R.id.txtReceiverTel);
        txtReceiverAddress = (TextView) findViewById(R.id.txtReceiverAddress);
        txtOrderInvoice = (TextView) findViewById(R.id.txtOrderInvoice);
        txtOrderPayment = (TextView) findViewById(R.id.txtOrderPayment);
        txtBuyerWords = (TextView) findViewById(R.id.txtBuyerWords);
        txtGjValue = (TextView) findViewById(R.id.txtGjValue);
        txtTotalValue = (TextView) findViewById(R.id.txtTotalValue);
        tv_envelop = (TextView) findViewById(R.id.tv_envelop);
        tvOrderOriginPrice = (TextView) findViewById(R.id.tv_goods_price);
        tvCuxiaoDiscount = (TextView) findViewById(R.id.tv_preferential);
        tvCouponDiscount = (TextView) findViewById(R.id.tv_goods_coupon_deduction);
        tvDealerEnvelopDed = (TextView) findViewById(R.id.tv_dealer_envelop_deduction);
        llytShopContainer = (LinearLayout) findViewById(R.id.llytShopContainer);
        llPromotionArea = (LinearLayout) findViewById(R.id.ll_promotion_area);
        llPayContainer = (LinearLayout) findViewById(R.id.llPayContainer);
        rlytOrderBuyerWords = (RelativeLayout) findViewById(R.id.rlytOrderBuyerWords);
        rlytOrderInvoiceMsg = (RelativeLayout) findViewById(R.id.rlytOrderInvoiceMsg);
        rlytGjLayout = (RelativeLayout) findViewById(R.id.rlytGjLayout);
        mRlOrderOriginPrice = (RelativeLayout) findViewById(R.id.rl_order_originpri);
        mRlCuxiaoDis = (RelativeLayout) findViewById(R.id.rl_cuxiao_dis);
        mRlGoodsCouponDis = (RelativeLayout) findViewById(R.id.rl_goods_coupon_dis);
        mRlDealersEnvelopDis = (RelativeLayout) findViewById(R.id.rl_dealers_envelop);
        mRlDanluEnvelopDis = (RelativeLayout) findViewById(R.id.rl_danlu_envelop_dis);
        rlytTotalLayout = (RelativeLayout) findViewById(R.id.rlytTotalLayout);
        imgOrderDetail = (ImageView) findViewById(R.id.imgOrderDetail);

        ofvOrder = (OrderFunctionView) findViewById(R.id.ofv_order);
    }

    @SuppressLint("SetTextI18n")
    private void setOrderDetailData(OrderDetailBean orderDetail) {
        // 设置订单号
        txtOrderBigNum.setText(orderDetail.getPaymentNo());
        // 设置子订单号
        txtOrderSmallNum.setText(orderDetail.getOrderNo());
        // 设置下单时间
        txtPlaceOrderTime.setText(orderDetail.getPlaceOrderTime());
        // 设置配送商
        txtPlaceOrderDispatch.setText(orderDetail.getSellerName());
        // 设置收货人
        txtReceiverName.setText(orderDetail.getDeliverAddress().getDeliverPerson());
        // 设置电话
        txtReceiverTel.setText(orderDetail.getDeliverAddress().getDeliverMobile());
        // 设置地址
        txtReceiverAddress.setText(orderDetail.getDeliverAddress().getDeliverAddress());

        // 设置发票信息
        if (orderDetail.getInvoice().getInvoiceType() != null) {
            if (orderDetail.getInvoice().getInvoiceType().equals(CommonConst.MyOrderDetailConst.NORMAL_INVOICE)) {
                txtOrderInvoice.setText(R.string.normal_invoice);
            } else if (orderDetail.getInvoice().getInvoiceType().equals(CommonConst.MyOrderDetailConst.ADD_INVOICE)) {
                txtOrderInvoice.setText(R.string.add_invoice);
            }

            intent.putExtra("NORMAL_INVOICE_HEADER", orderDetail.getInvoice().getInvoiceHeader());
            intent.putExtra(CommonConst.MyOrderDetailConst.ORDER_SORT, orderDetail.getInvoice().getInvoiceType());
            intent.putExtra(CommonConst.MyOrderDetailConst.COMPANY_NAME, orderDetail.getInvoice().getCompanyName());
            intent.putExtra(CommonConst.MyOrderDetailConst.PERSON_NUM, orderDetail.getInvoice().getTaxpayerRegistrationNumber());
            imgOrderDetail.setVisibility(View.VISIBLE);
        } else {
            txtOrderInvoice.setText(R.string.invoice_nodata_label);
            rlytOrderInvoiceMsg.setClickable(false);
            imgOrderDetail.setVisibility(View.INVISIBLE);
        }

        // 设置支付时间
        List<OrderDetailBean.PayTimeListBean> payTimeList = orderDetail.getPayTimeList();
        setPayListTimeView(payTimeList, orderDetail.getPayTime(), orderDetail.getOrderStatus());

        // 设置买家留言
        if (orderDetail.getComment() != null && !orderDetail.getComment().equals("")) {
            txtBuyerWords.setText(orderDetail.getComment());
            intent.putExtra(CommonConst.MyOrderDetailConst.ORDER_DETAIL, orderDetail.getComment());
        } else {
            rlytOrderBuyerWords.setVisibility(View.GONE);
        }

        switch (orderDetail.getPayType()) {
            case CommonConst.MyOrderConst.ONLINE: // 在线支付
                // 设置支付方式
                txtOrderPayment.setText(getResources().getString(R.string.pay_online));
                break;

            case CommonConst.MyOrderConst.ARRIVE: // 货到付款
                // 设置支付方式
                txtOrderPayment.setText(getResources().getString(R.string.pay_arrive));
                break;

            case CommonConst.MyOrderConst.COMPANY: // 公司转账
                // 设置支付方式
                txtOrderPayment.setText(getResources().getString(R.string.pay_company_change));
                break;

            case CommonConst.MyOrderConst.ONLINE_ARRIVE: // 混合支付
                // 设置支付方式
                txtOrderPayment.setText(getResources().getString(R.string.pay_online) + "+" + getResources().getString(R.string.pay_arrive));
                break;

            default:
                break;
        }
        for (MerchListBean merchList : orderDetail.getMerchList()) {
            shopNum = shopNum + Integer.parseInt(merchList.getMerchCount());
        }
        // 设置总价
        txtTotalValue.setText(getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(orderDetail.getTotalPrice())).toString());
        // 添加商品
        addShopLinear(orderDetail.getMerchList());
        // 添加促销
        addPromotionArea(orderDetail.getTotalDiscountOrderAmt());

        // 订单改价显示
        String orderDiscountAmount = orderDetail.getOrderDiscountAmount();
        if (!TextUtils.isEmpty(orderDiscountAmount)) {
            String changeOrderPrice = orderDiscountAmount.replace("-", "");
            if (CalculatePriceUtil.compare(changeOrderPrice, 0 + "") != 0) {
                String s = CommonUtils.formateRate(CommonUtils.fenToYuan(new BigDecimal(changeOrderPrice)).toPlainString());
                rlytGjLayout.setVisibility(View.VISIBLE);
                if (orderDiscountAmount.contains("-")) {
                    //加价
                    s = "+￥" + s;
                } else {
                    s = "-￥" + s;
                }
                txtGjValue.setText(s);
            } else {
                rlytGjLayout.setVisibility(View.GONE);
            }
        } else {
            rlytGjLayout.setVisibility(View.GONE);
        }
        //促销优惠
        String cuxiaoDis = orderDetail.getTotalDiscountAmt();
        if (!TextUtils.isEmpty(cuxiaoDis) && CalculatePriceUtil.compare(cuxiaoDis, 0 + "") != 0) {
            mRlCuxiaoDis.setVisibility(View.VISIBLE);
            BigDecimal decimal = CommonUtils.fenToYuan(new BigDecimal(cuxiaoDis));
            tvCuxiaoDiscount.setText("-￥ " + CommonUtils.formateRate(decimal.toPlainString()));
        } else {
            mRlCuxiaoDis.setVisibility(View.GONE);
        }
        // 经销商商品优惠券抵扣
        String goodsCouponDis = orderDetail.getDealerBenefitUseAmt();
        if (!TextUtils.isEmpty(goodsCouponDis) && CalculatePriceUtil.compare(goodsCouponDis, 0 + "") != 0) {
            mRlGoodsCouponDis.setVisibility(View.VISIBLE);
            BigDecimal dealerBenefitUseAmtBD = CommonUtils.fenToYuan(new BigDecimal(goodsCouponDis));
            tvCouponDiscount.setText("-￥ " + CommonUtils.formateRate(dealerBenefitUseAmtBD.toPlainString()));
        } else {
            mRlGoodsCouponDis.setVisibility(View.GONE);
        }
        // 经销商红包抵扣
        String dealersEnvelopDis = orderDetail.getDealerCouponUseAmt();
        if (!TextUtils.isEmpty(dealersEnvelopDis) && CalculatePriceUtil.compare(dealersEnvelopDis, 0 + "") != 0) {
            mRlDealersEnvelopDis.setVisibility(View.VISIBLE);
            BigDecimal dealerEnvelopUseAmtBD = CommonUtils.fenToYuan(new BigDecimal(dealersEnvelopDis));
            tvDealerEnvelopDed.setText("-￥ " + CommonUtils.formateRate(dealerEnvelopUseAmtBD.toPlainString()));
        } else {
            mRlDealersEnvelopDis.setVisibility(View.GONE);
        }
        //丹露红包抵扣
        String danluEnvelopDis = orderDetail.getCouponUseAmt();
        if (!TextUtils.isEmpty(danluEnvelopDis) && CalculatePriceUtil.compare(danluEnvelopDis, 0 + "") != 0) {
            mRlDanluEnvelopDis.setVisibility(View.VISIBLE);
            BigDecimal danluEnvelopDisBd = CommonUtils.fenToYuan(new BigDecimal(danluEnvelopDis));
            tv_envelop.setText("-￥ " + CommonUtils.formateRate(danluEnvelopDisBd.toPlainString()));
        } else {
            mRlDanluEnvelopDis.setVisibility(View.GONE);
        }
        // 设置是否显示按钮
        setSmallOrderBtnIsVisible(orderDetail.getButtomList());
        // 商品原价
        String totalMerchAmt = orderDetail.getTotalMerchAmt();
        if (!TextUtils.isEmpty(totalMerchAmt)) {
            BigDecimal decimal = CommonUtils.fenToYuan(new BigDecimal(totalMerchAmt));
            tvOrderOriginPrice.setText("￥ " + CommonUtils.formateRate(decimal.toPlainString()));
            View view = (View) tvOrderOriginPrice.getParent();
            view.setVisibility(View.VISIBLE);
        }
        if (null == headerWrapper) {
            headerWrapper = new OrderStatusHeaderWrapper(findViewById(R.id.ll_order_header));
        }
        headerWrapper.setOrderStatus(orderDetail.getOrderStatus(), orderDetail.getCancelStatus());
        headerWrapper.setCancelReason(orderDetail.getCancelReason());
    }

    private void addPromotionArea(final String totalDiscountAmt) {
        if (null != orderDetail.getPromotionList() && !orderDetail.getPromotionList().isEmpty()) {
            llPromotionArea.setVisibility(View.VISIBLE);
            final TextView tvGift = (TextView) findViewById(R.id.tv_gift);
            final TextView tvDiscount = (TextView) findViewById(R.id.tv_discount);

            if (TextUtils.isEmpty(totalDiscountAmt) || "0".equals(totalDiscountAmt)) {
                findViewById(R.id.ll_discount).setVisibility(View.GONE);
            } else {
                findViewById(R.id.ll_discount).setVisibility(View.VISIBLE);
                tvDiscount.setText("￥".concat(CommonUtils.fenToYuan(new BigDecimal(totalDiscountAmt)).toPlainString()));
            }

            if (TextUtils.isEmpty(getGiftInfo())) {
                tvGift.setVisibility(View.GONE);
            } else {
                tvGift.setVisibility(View.VISIBLE);
                tvGift.setText("促销赠送：" + getGiftInfo());
            }

            llPromotionArea.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO: 2017/3/17 点击弹窗 - 优惠信息细节 @lyf #ok
                    // TODO: 2017/3/26 满赠弹窗显示有问题，需要修正 @lyf #ok
                    PromotionDetailPopup promotionDetailPopup = new PromotionDetailPopup(DeliveryDetailActivity.this, totalDiscountAmt, orderDetail.getPromotionList());
                    promotionDetailPopup.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                }
            });
        } else {
            llPromotionArea.setVisibility(View.GONE);
        }
    }

    private String getGiftInfo() {
        String giftMsg = "";
        for (OrderDetailBean.PromotionListBean promotion : orderDetail.getPromotionList()) {
            if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_0.equals(promotion.getPromotionType())) {
                giftMsg = giftMsg.concat(promotion.getPromotionDetail()).concat(";");
            }
        }
        return giftMsg;
    }

    /**
     * 支付单号适配问题  可以采用google的FlextLayout 实现更为优雅->why
     */
    private void setPayListTimeView(List<OrderDetailBean.PayTimeListBean> payTimeList, String singleTime, String orderStatus) {
        if (!orderStatus.equals("C025")) {
            llPayContainer.setVisibility(View.GONE);
            txtPayTime.setText(!TextUtils.isEmpty(singleTime) ? singleTime : "");
            return;
        }
        txtPayTime.setText("");
        llPayContainer.removeAllViews();
        llPayContainer.setVisibility(View.VISIBLE);
        for (int i = 0; i < payTimeList.size(); i++) {
            OrderDetailBean.PayTimeListBean model = payTimeList.get(i);
            View childView = View.inflate(this, R.layout.item_orderdetail_split, null);
            TextView tvNewLinePayNo = (TextView) childView.findViewById(R.id.tv_paynewline_no);
            TextView tvPayNo = (TextView) childView.findViewById(R.id.tv_pay_no);
            TextView tvPayTime = (TextView) childView.findViewById(R.id.tv_pay_time);
            TextView tvAmount = (TextView) childView.findViewById(R.id.tv_pay_amount);
            boolean isChangeLine = judgeIsChangeLine(model.getSeparatePaymentNo());
            String payNoStr = String.format(getResources().getString(R.string.dl_item_payno_str), model.getSeparatePaymentNo());
            if (isChangeLine) {
                tvNewLinePayNo.setVisibility(View.VISIBLE);
                tvPayNo.setVisibility(View.GONE);
                tvNewLinePayNo.setText(payNoStr);
            } else {
                tvPayNo.setVisibility(View.VISIBLE);
                tvPayNo.setText(payNoStr);
                tvNewLinePayNo.setVisibility(View.GONE);
            }
            BigDecimal yuan = CommonUtils.fenToYuan(new BigDecimal(model.getSeparateOrderAmount()));
            tvAmount.setText(String.format(getResources().getString(R.string.dl_item_pay_amount), yuan.toPlainString()));
            tvPayTime.setText(model.getTime());
            if (i != 0) {
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(0, DensityUtils.dip2px(this, 10), 0, 0);
                childView.setLayoutParams(lp);
            }
            llPayContainer.addView(childView);
        }
    }

    /***
     * 添加商品布局
     */
    @SuppressLint("SetTextI18n")
    private void addShopLinear(List<MerchListBean> merchList) {
        llytShopContainer.removeAllViewsInLayout();
        for (int i = 0; i < merchList.size(); i++) {
            final MerchListBean model = merchList.get(i);
            @SuppressLint("InflateParams")
            View view = LayoutInflater.from(this).inflate(R.layout.item_order_shop_merchinfo, null);
            SimpleDraweeView orderShopGoodsImg = (SimpleDraweeView) view.findViewById(R.id.sdv_merch);
            TextView orderShopGoodsMsg = (TextView) view.findViewById(R.id.tv_merch_name);
            TextView oldOrderShopGoodsPrice = (TextView) view.findViewById(R.id.tv_old_price);
            TextView newOrderShopGoodsPrice = (TextView) view.findViewById(R.id.tv_new_price);
            TextView orderShopGoodsBar = (TextView) view.findViewById(R.id.tv_barcode);
            TextView orderShopGoodsNum = (TextView) view.findViewById(R.id.tv_merch_count);
            TextView tvSnapshot = (TextView) view.findViewById(R.id.tv_snapshot);
            TextView tvPriceDetail = (TextView) view.findViewById(R.id.tv_price_detail);

            if (i == merchList.size() - 1) {
                view.findViewById(R.id.v_line).setVisibility(View.GONE);
            }
            tvSnapshot.setVisibility(View.VISIBLE);
            tvSnapshot.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 设置订单号
                    Intent intent = new Intent();
                    intent.putExtra(CommonConst.MyOrderConst.SMALL_ORDER_P_KEY, orderId);
                    // 设置商品id
                    intent.putExtra(CommonConst.MyOrderConst.SMALL_ORDER_SHOP_NUM, model.getMerchId());
                    intent.setClass(DeliveryDetailActivity.this, DeliverLookForPhotoActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }
            });
            // 设置商品名
            orderShopGoodsMsg.setText(model.getMerchName());
            if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4.equals(model.getPromotionType())) {// 限购
                oldOrderShopGoodsPrice.setVisibility(View.VISIBLE);
                tvPriceDetail.setVisibility(View.VISIBLE);

                oldOrderShopGoodsPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                oldOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getUnitPrice())).toString());
                newOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getAveragePrice())).toString());

                // TODO: 2017/3/17 弹出价格详情 @lyf #ok
                tvPriceDetail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MerchPricePopupView pricePopupView = new MerchPricePopupView(DeliveryDetailActivity.this, model);
                        pricePopupView.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                    }
                });
            } else if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1.equals(model.getPromotionType())) { // 满减
                if (TextUtils.isEmpty(model.getReduceValue())) {
                    // 满减单
                    oldOrderShopGoodsPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                    oldOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getCostPrice())).toString());
                    newOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getUnitPrice())).toString());
                } else {
                    // 满减总
                    oldOrderShopGoodsPrice.setVisibility(View.GONE);
                    newOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getUnitPrice())).toString());
                }
            } else {
                oldOrderShopGoodsPrice.setVisibility(View.GONE);
                newOrderShopGoodsPrice.setText(getResources().getString(R.string.rmb_unit_label) + CommonUtils.fenToYuan(new BigDecimal(model.getUnitPrice())).toString());
            }
            // 设置商品码
            orderShopGoodsBar.setText(model.getMerchBarCode());
            // 设置数量
            orderShopGoodsNum.setText(model.getMerchCount());
            // 下载图片
            orderShopGoodsImg.setImageURI(model.getPicUrl());
            llytShopContainer.addView(view);
        }
    }

    /**
     * 设置子订单是否显示按钮
     */
    private void setSmallOrderBtnIsVisible(String bottomList) {
        ofvOrder.refreshButton(bottomList);
    }

    private boolean judgeIsChangeLine(String separatePaymentNo) {
        TextView textView = new TextView(this);
        textView.setTextSize(13);
        textView.setTextColor(getResources().getColor(R.color.color_888888));
        SpannableString s = new SpannableString(String.format(getResources().getString(R.string.dl_item_payno_str), separatePaymentNo));
        int width = CommonUtils.getScreenWidth(this) - CommonUtils.dipToPx(this, 35); // paddingleft+paddingright+margiright+marginleft == 35
        StaticLayout staticLayout = new StaticLayout(s, textView.getPaint(), width * 2 / 3, Layout.Alignment.ALIGN_NORMAL, 1, 0.0f, false);
        return staticLayout.getLineCount() > 1;
    }

    /**
     * 创建收货对话框
     */
    private void createOrderReceiveDialog() {
        // 创建Builder
        ViewDialog.Builder builder = new ViewDialog.Builder(this);
        // 设置信息
        builder.setMessage(R.string.myself_order_deal_receive_dialog);
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 确认收货请求类
                OrderOperReceiveRequest request = new OrderOperReceiveRequest();
                // 设置token
                request.setToken(agent.getToken());
                // 设置大订单
                request.setPaymentNo(orderDetail.getPaymentNo());
                // 设置订单号
                request.setOrderNo(orderDetail.getOrderNo());
                // 设置交易类型
                request.setPayType(orderDetail.getPayType());

                receiveOrder(request);
                // 对话框关闭
                dialog.dismiss();
            }
        });

        // 设置Negative按钮点击监听
        builder.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 对话框关闭
                dialog.dismiss();
            }
        });
        // 对话框不可取消
        builder.setCancelable(true);
        // 创建对话框并显示
        builder.create().show();
    }

    private void receiveOrder(OrderOperReceiveRequest request) {
        agent.getApi()
                .orderReceive(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(this, R.string.receive_goods_ing) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.getInstance().show("确认收货成功");
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        if (code.equals("1")) {
                            getOrderDetail();
                            return "订单状态发生改变,请刷新订单列表";
                        }
                        return super.parseBussinessException(code);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    protected void skipOrderTrackActivity() {
        Intent intent = new Intent(this, OrderTrackActivity.class);
        intent.putExtra("orderNo", orderDetail.getOrderNo());
        startActivity(intent);
    }


}